'use strict';
const limitSize = 0
const db = uniCloud.database()
exports.main = async (event, context) => {
	//event为客户端上传的参数
	console.log('event : ', event)
	var { url } = event.queryStringParameters
	// console.log("url", url)
	// url = "https://img.xiumi.us/xmi/ua/2GJkT/i/bb517378fbeaeb213b9c90f21c2e8913-sz_4367062.jpg?x-oss-process=style/xm"
	if (!url) {
		return {
			"statusCode": 400
		}
	}
	url = decodeURIComponent(url)
	// let url = "https://img.xiumi.us/xmi/ua/2GJkT/i/bb517378fbeaeb213b9c90f21c2e8913-sz_4367062.jpg?x-oss-process=style/xm"
	var res = await db.collection("file-cache").where({
		srcUrl: url
	}).get()
	if (res.data.length) {
		return {
			mpserverlessComposedResponse: false, // 使用阿里云返回集成响应是需要此字段为true
			isBase64Encoded: false,
			statusCode: 301,
			headers: {
				'location': res.data[0].cachedUrl
			}
		}
	}
	res = await uniCloud.httpclient.request(url, {
	    method: 'GET',
		timeout: 60000
	})
	let contentLength = parseInt(res.headers["content-length"])
	console.log("contentLength", contentLength + '')
	if (contentLength < limitSize) {
		return {
			"mpserverlessComposedResponse": false,
			"isBase64Encoded": true,
			"statusCode": res.status,
			"headers": {
				"content-type": res.headers['content-type']
			},
			"body": res.data
		}
	} else {
		let contentType = res.headers["content-type"]
		let t = url.split('?')[0]
		let fileName = t.substring(t.lastIndexOf('/') + 1, t.length)
		res = await uniCloud.uploadFile({
			cloudPath: "fileCache/" + fileName,
			fileContent: res.data
		})
		let {fileID} = res
		res = await uniCloud.getTempFileURL({
			fileList: [fileID]
		})
		let {fileList} = res
		await db.collection("file-cache").add({
			srcUrl: url,
			cachedUrl: fileList[0].download_url,
			fileID: fileID
		})
		return {
			mpserverlessComposedResponse: false, // 使用阿里云返回集成响应是需要此字段为true
			isBase64Encoded: false,
			statusCode: 301,
			headers: {
				'location': fileList[0].download_url
			}
		}
	}
	
	// let result = {
	// 	"mpserverlessComposedResponse": false,
	// 	"isBase64Encoded": false,
	// 	"statusCode": res.status,
	// 	"headers": {
	// 		"content-type": res.headers['content-type']
	// 	},
	// 	"body": res.data
	// }
	// return result
};
